package com.facebook.base;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;


import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;

import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
import com.facebook.base.SessionEvents.AuthListener;
import com.facebook.base.SessionEvents.LogoutListener;



public class FacebookConnector {

	private Facebook facebook = null;
	private Context context;
	private String[] permissions;
	private Handler mHandler;
	private Activity activity;
	private SessionListener mSessionListener = new SessionListener();;
	
	public FacebookConnector(String appId,Activity activity,Context context,String[] permissions) {
		this.facebook = new Facebook(appId);
		
		SessionStore.restore(facebook, context);
        SessionEvents.addAuthListener(mSessionListener);
        SessionEvents.addLogoutListener(mSessionListener);
        
		this.context		=	context;
		this.permissions	=	permissions;
		this.mHandler 		= 	new Handler();
		this.activity		=	activity;
	}
	
	public void login() {
        if (!facebook.isSessionValid()) {
            facebook.authorize(this.activity, this.permissions,new LoginDialogListener());
        }
    }
	
	public void logout() {
        SessionEvents.onLogoutBegin();
        AsyncFacebookRunner asyncRunner = new AsyncFacebookRunner(this.facebook);
        asyncRunner.logout(this.context, new LogoutRequestListener());
	}
	
	public void postMessageOnWall(String msg, String link, String name, String description) {
		if (facebook.isSessionValid()) {
		    Bundle parameters = new Bundle();
		    
		    if ((msg == null) || (msg != null && msg.length() ==0))
		    	parameters.putString("message", "GO!!");
		    else
		    	parameters.putString("message", msg);
		    
		    if (name != null && name.length() != 0)
		    	parameters.putString("name", name);
		    
		    if (description != null && description.length() != 0)
		    	parameters.putString("description", description);
		    
		    if (link != null && link.length() != 0)
		    	parameters.putString("link", link);
		    
		    try {
				String response = facebook.request("me/feed", parameters,"POST");
				System.out.println(response);
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			login();
		}
	}
	
	public void postImageOnWall(Bitmap bi, String msg, String link){
		if (facebook.isSessionValid()) {
			byte[] data = null;
         
	        ByteArrayOutputStream baos = new ByteArrayOutputStream();              
	        bi.compress(Bitmap.CompressFormat.JPEG, 100, baos);              
	        data = baos.toByteArray();                
	        Bundle parameters = new Bundle();
	        parameters.putString("message", msg);
	        parameters.putString("link", link);
	        //parameters.putString(Facebook.TOKEN, facebook.getAccessToken());              
	        //parameters.putString("method", "photos.upload");              
	        parameters.putByteArray("picture", data);
	        
		    try {
				String response = facebook.request("me/photos", parameters,"POST");
				System.out.println(response);
			} catch (IOException e) {
				e.printStackTrace();
			}	        
		} else {
			login();
		}
		
	}
	
	public JSONObject requestUserInfo() {
		JSONObject me = null;
		if (facebook.isSessionValid()) {			
			try {
				me = new JSONObject(facebook.request("me"));
				System.out.println(me);
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}	        
		} else {
			login();
		}
		return me;
	}

    private final class LoginDialogListener implements DialogListener {
        public void onComplete(Bundle values) {
            SessionEvents.onLoginSuccess();
        }

        public void onFacebookError(FacebookError error) {
            SessionEvents.onLoginError(error.getMessage());
        }
        
        public void onError(DialogError error) {
            SessionEvents.onLoginError(error.getMessage());
        }

        public void onCancel() {
            SessionEvents.onLoginError("Action Canceled");
        }
    }
    
    public class LogoutRequestListener extends BaseRequestListener {
        public void onComplete(String response, final Object state) {
            // callback should be run in the original thread, 
            // not the background thread
            mHandler.post(new Runnable() {
                public void run() {
                    SessionEvents.onLogoutFinish();
                }
            });
        }
    }
    
    private class SessionListener implements AuthListener, LogoutListener {
        
        public void onAuthSucceed() {
            SessionStore.save(facebook, context);
        }

        public void onAuthFail(String error) {
        }
        
        public void onLogoutBegin() {           
        }
        
        public void onLogoutFinish() {
            SessionStore.clear(context);
        }
    }

	public Facebook getFacebook() {
		return this.facebook;
	}
}
